# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from core.libs import vkontakte
from apps.vkontakte.models import WallRecord, VKUser, VKNew
import time
import datetime
import logging

class Command(BaseCommand):	
    def handle(self, *args, **options):

        logger = logging.getLogger()

        news = VKNew.objects.filter(status=VKNew.STATUS_UNDEFINED)#.values_list('pk', flat=True)
        if not news.count():
            return ""
            
        news.update(status=VKNew.STATUS_IN_PROGRESS)
        
        news = VKNew.objects.filter(status=VKNew.STATUS_IN_PROGRESS)

        message = "%s" % news[0].message.encode("utf-8", "ignore")
        logger.info(message)
        news.update(status=VKNew.STATUS_READY)

        vk = vkontakte.API("2023356", "thdXZZOEaK4hUKu9Q2Am")

        x = 100
        users = VKUser.objects.all()
        iters = int(len(users)/x)+1
        for i in range(0, iters):
            uids = [str(user.uid) for user in users[(i*x):(i*x)+x]]
            uids_list = ",".join(uids)
            
            future = datetime.datetime.now() + datetime.timedelta(hours=2)

            response = vk.secure.sendNotification(
                timestamp = int(time.mktime(future.timetuple())),
                uids = uids_list,
                message = message
            )
            response_uids = response.split(",")
            
            remove_uids = list(set(uids) ^ set(response_uids))
            VKUser.objects.filter(uid__in = remove_uids).delete()
            
            logger.info(response)



